package com.ruoyi.business.controller;

import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.itextpdf.text.DocumentException;
import com.ruoyi.business.domain.Beds;
import com.ruoyi.business.domain.Employee;
import com.ruoyi.business.domain.HisGuest;
import com.ruoyi.business.domain.vo.EmployeePdf;
import com.ruoyi.business.mapper.EmployeePlusMapper;
import com.ruoyi.business.service.IBedsPlusService;
import com.ruoyi.business.service.IEmployeePlusService;
import com.ruoyi.business.tools.objectToMapTool;
import com.ruoyi.business.tools.pdfTool;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.excel.ExcelResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.MimeTypeUtils;
import com.ruoyi.common.utils.poi.ExcelUtilPlus;
import com.ruoyi.system.domain.SysNotice;
import com.ruoyi.system.service.ISysNoticeService;
import lombok.RequiredArgsConstructor;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.*;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.business.domain.vo.EmployeeVo;
import com.ruoyi.business.domain.bo.EmployeeBo;
import com.ruoyi.business.service.IEmployeeService;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

import java.lang.reflect.Type;

/**
 * 员工
 *
 * @author ruoyi
 * @date 2023-06-21
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/business/employee")
public class EmployeeController extends BaseController {

    private final IEmployeeService iEmployeeService;
    private final IBedsPlusService bedsPlusService;
    private final IEmployeePlusService employeePlusService;
    // private final IWfProcessService processService;
    private final ISysNoticeService sysNoticeService;
    /**
     * 查询员工列表
     */
    @GetMapping("/list")
    public TableDataInfo<EmployeeVo> list(EmployeeBo entity, PageQuery pageQuery) {
        if (entity.getEntryDateArray() != null && entity.getEntryDateArray().length >= 2) {
            entity.setEntryDateStart(entity.getEntryDateArray()[0]);
            entity.setEntryDateEnd(entity.getEntryDateArray()[1]);
        }
        if (entity.getHousingFundStartDateArray() != null && entity.getHousingFundStartDateArray().length >= 2) {
            entity.setHousingFundStartDateStart(entity.getHousingFundStartDateArray()[0]);
            entity.setHousingFundStartDateEnd(entity.getHousingFundStartDateArray()[1]);
        }
        //参保时间
        if (entity.getInsuranceStartDateArray() != null && entity.getInsuranceStartDateArray().length >= 2) {
            entity.setInsuranceStartDateStart(entity.getInsuranceStartDateArray()[0]);
            entity.setInsuranceStartDateEnd(entity.getInsuranceStartDateArray()[1]);
        }
        //退保时间
        if (entity.getInsuranceEndDateArray() != null && entity.getInsuranceEndDateArray().length >= 2) {
            entity.setInsuranceEndDateStart(entity.getInsuranceEndDateArray()[0]);
            entity.setInsuranceEndDateEnd(entity.getInsuranceEndDateArray()[1]);
        }
        //首次签订到期时间
        if (entity.getFirstContractExpiryDateArray() != null && entity.getFirstContractExpiryDateArray().length >= 2) {
            entity.setFirstContractExpiryDateStart(entity.getFirstContractExpiryDateArray()[0]);
            entity.setFirstContractExpiryDateEnd(entity.getFirstContractExpiryDateArray()[1]);
        }
        //2次签订到期时间
        if (entity.getSecondContractExpiryDateArray() != null && entity.getSecondContractExpiryDateArray().length >= 2) {
            entity.setSecondContractExpiryDateStart(entity.getSecondContractExpiryDateArray()[0]);
            entity.setSecondContractExpiryDateEnd(entity.getSecondContractExpiryDateArray()[1]);
        }
        //3次签订到期时间
        if (entity.getThirdContractExpiryDateArray() != null && entity.getThirdContractExpiryDateArray().length >= 2) {
            entity.setThirdContractExpiryDateStart(entity.getThirdContractExpiryDateArray()[0]);
            entity.setThirdContractExpiryDateEnd(entity.getThirdContractExpiryDateArray()[1]);
        }
        //4次签订到期时间
        if (entity.getFourthContractExpiryDateArray() != null && entity.getFourthContractExpiryDateArray().length >= 2) {
            entity.setFourthContractExpiryDateStart(entity.getFourthContractExpiryDateArray()[0]);
            entity.setFourthContractExpiryDateEnd(entity.getFourthContractExpiryDateArray()[1]);
        }
        //5次签订到期时间
        if (entity.getFifthContractExpiryDateArray() != null && entity.getFifthContractExpiryDateArray().length >= 2) {
            entity.setFifthContractExpiryDateStart(entity.getFifthContractExpiryDateArray()[0]);
            entity.setFifthContractExpiryDateEnd(entity.getFifthContractExpiryDateArray()[1]);
        }
        //离职时间
        if (entity.getDepartureDateArray() != null && entity.getDepartureDateArray().length >= 2) {
            entity.setDepartureDateStart(entity.getDepartureDateArray()[0]);
            entity.setDepartureDateEnd(entity.getDepartureDateArray()[1]);
        }
        return iEmployeeService.queryPageList(entity, pageQuery);
    }

    /**
     * 导入数据
     *
     * @param file          导入文件
     * @param updateSupport 是否更新已存在数据
     */
    @Log(title = "员工", businessType = BusinessType.IMPORT)
    @PostMapping(value = "/importData", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<Void> importData(@RequestPart("file") MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtilPlus<Employee> util = new ExcelUtilPlus<>(Employee.class);
        List<Employee> userList = util.importExcel(file.getInputStream());
        Date updateTime = new Date();
        userList.forEach(employee -> {
            employee.setOutsource("否");
            employee.setUpdateTime(updateTime);
            switch (employee.getDelFlag()) {
                case "在职":
                    employee.setDelFlag("0");
                    break;
                case "离职":
                    employee.setDelFlag("1");
                    break;
                case "删除":
                    employee.setDelFlag("2");
                    break;
                default:
                    employee.setDelFlag("0");
                    break;
            }
            try {
                LambdaUpdateWrapper<Employee> updateWrapper = new LambdaUpdateWrapper<Employee>()
                    .eq(Employee::getJobNumber, employee.getJobNumber())
                    .eq(Employee::getIdNumber,employee.getIdNumber());//根据工号和身份证进行条件修改
                employeePlusService.saveOrUpdate(employee, updateWrapper);
            } catch (DuplicateKeyException e) {
                System.out.println("跳过的错误数据: " + e.getMessage());
            }
        });
        return R.ok();
    }

    /**
     * 外包人员导入数据
     *
     * @param file          导入文件
     * @param updateSupport 是否更新已存在数据
     */
    @Log(title = "员工", businessType = BusinessType.IMPORT)
    @PostMapping(value = "/importData2", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<Void> importData2(@RequestPart("file") MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtilPlus<Employee> util = new ExcelUtilPlus<>(Employee.class);
        List<Employee> userList = util.importExcel(file.getInputStream());
        Date updateTime = new Date();
        userList.forEach(employee -> {
            employee.setOutsource("是");
            employee.setUpdateTime(updateTime);
            switch (employee.getDelFlag()) {
                case "在职":
                    employee.setDelFlag("0");
                    break;
                case "离职":
                    employee.setDelFlag("1");
                    break;
                case "删除":
                    employee.setDelFlag("2");
                    break;
                default:
                    employee.setDelFlag("0");
                    break;
            }
            try {
                LambdaUpdateWrapper<Employee> updateWrapper = new LambdaUpdateWrapper<Employee>()
                    .eq(Employee::getJobNumber, employee.getJobNumber())
                    .eq(Employee::getIdNumber,employee.getIdNumber());//根据工号和身份证进行条件修改
                employeePlusService.saveOrUpdate(employee, updateWrapper);
            } catch (DuplicateKeyException e) {
                System.out.println("跳过的错误数据: " + e.getMessage());
            }
        });
        return R.ok();
    }

    /**
     * 导出员工列表
     */
    @Log(title = "员工", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(EmployeeBo entity, HttpServletResponse response) throws ParseException {
        if (entity.getEntryDateArray() != null && entity.getEntryDateArray().length >= 2) {
            entity.setEntryDateStart(entity.getEntryDateArray()[0]);
            entity.setEntryDateEnd(entity.getEntryDateArray()[1]);
        }
        if (entity.getHousingFundStartDateArray() != null && entity.getHousingFundStartDateArray().length >= 2) {
            entity.setHousingFundStartDateStart(entity.getHousingFundStartDateArray()[0]);
            entity.setHousingFundStartDateEnd(entity.getHousingFundStartDateArray()[1]);
        }
        //参保时间
        if (entity.getInsuranceStartDateArray() != null && entity.getInsuranceStartDateArray().length >= 2) {
            entity.setInsuranceStartDateStart(entity.getInsuranceStartDateArray()[0]);
            entity.setInsuranceStartDateEnd(entity.getInsuranceStartDateArray()[1]);
        }
        //退保时间
        if (entity.getInsuranceEndDateArray() != null && entity.getInsuranceEndDateArray().length >= 2) {
            entity.setInsuranceEndDateStart(entity.getInsuranceEndDateArray()[0]);
            entity.setInsuranceEndDateEnd(entity.getInsuranceEndDateArray()[1]);
        }
        //首次签订到期时间
        if (entity.getFirstContractExpiryDateArray() != null && entity.getFirstContractExpiryDateArray().length >= 2) {
            entity.setFirstContractExpiryDateStart(entity.getFirstContractExpiryDateArray()[0]);
            entity.setFirstContractExpiryDateEnd(entity.getFirstContractExpiryDateArray()[1]);
        }
        //2次签订到期时间
        if (entity.getSecondContractExpiryDateArray() != null && entity.getSecondContractExpiryDateArray().length >= 2) {
            entity.setSecondContractExpiryDateStart(entity.getSecondContractExpiryDateArray()[0]);
            entity.setSecondContractExpiryDateEnd(entity.getSecondContractExpiryDateArray()[1]);
        }
        //3次签订到期时间
        if (entity.getThirdContractExpiryDateArray() != null && entity.getThirdContractExpiryDateArray().length >= 2) {
            entity.setThirdContractExpiryDateStart(entity.getThirdContractExpiryDateArray()[0]);
            entity.setThirdContractExpiryDateEnd(entity.getThirdContractExpiryDateArray()[1]);
        }
        //4次签订到期时间
        if (entity.getFourthContractExpiryDateArray() != null && entity.getFourthContractExpiryDateArray().length >= 2) {
            entity.setFourthContractExpiryDateStart(entity.getFourthContractExpiryDateArray()[0]);
            entity.setFourthContractExpiryDateEnd(entity.getFourthContractExpiryDateArray()[1]);
        }
        //5次签订到期时间
        if (entity.getFifthContractExpiryDateArray() != null && entity.getFifthContractExpiryDateArray().length >= 2) {
            entity.setFifthContractExpiryDateStart(entity.getFifthContractExpiryDateArray()[0]);
            entity.setFifthContractExpiryDateEnd(entity.getFifthContractExpiryDateArray()[1]);
        }
        //离职时间
        if (entity.getDepartureDateArray() != null && entity.getDepartureDateArray().length >= 2) {
            entity.setDepartureDateStart(entity.getDepartureDateArray()[0]);
            entity.setDepartureDateEnd(entity.getDepartureDateArray()[1]);
        }
        PageQuery pageQuery = new PageQuery();
        pageQuery.setPageNum(1);
        pageQuery.setPageSize(500000);
        List<EmployeeVo> list = iEmployeeService.queryPageList(entity, pageQuery).getRows();
        list.forEach(employee -> {
            if(employee.getDelFlag().equals("0")){
                employee.setDelFlag("在职");
            }else  if(employee.getDelFlag().equals("1")){
                employee.setDelFlag("离职");
            }else  if(employee.getDelFlag().equals("2")){
                employee.setDelFlag("删除");
            }
        });
        //List<EmployeeVo> list = iEmployeeService.queryList(bo);
        // ExcelUtil.exportExcel(list, "员工", EmployeeVo.class, response);
        ExcelUtilPlus<EmployeeVo> util = new ExcelUtilPlus<EmployeeVo>(EmployeeVo.class);
        util.exportExcel(response, list, "员工");
    }

    /**
     * 获取员工详细信息
     *
     * @param id 主键
     */
    @GetMapping("/{id}")
    public R<Employee> getInfo(@NotNull(message = "主键不能为空") @PathVariable Long id) {
        Employee employee=employeePlusService.getById(id);
        if (employee.getRoomNumber()!=null&&!employee.getRoomNumber().isEmpty()){
            employee.setBeddetail(bedsPlusService.getbedDetailByid(employee.getRoomNumber()));
        }
        return R.ok(employee);
    }

    /**
     * 新增员工
     */
    @Transactional(rollbackFor = Exception.class)
    @Log(title = "员工", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody Employee bo) {
        // 生成一个随机的UUID
        UUID uuid = UUID.randomUUID();
        long id = uuid.getMostSignificantBits();
        bo.setId(id);
        if (employeePlusService.save(bo)) {
//            if (bo.getAccommodation().equals("是")){
//                String procDefKey = "Process_1689731712802";
//                Map<String, Object> variables = objectToMapTool.objectToMap(bo);
//                processService.startProcessByDefKey(procDefKey, variables);
//            }
        }
        return toAjax(true);
    }

    /**
     * 修改员工
     */
    @Log(title = "员工", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody Employee bo) {
        if (bo.getDelFlag().equals("1")&&bo.getAccommodation().equals("是")&& bo.getRoomNumber() != null) {
            //之前离职是自动清空床位的，后来加了通知，就让手动操作了
//            LambdaUpdateWrapper<Beds> update_beds_sql2 = new LambdaUpdateWrapper<Beds>().set(Beds::getEmployeeId, null).set(Beds::getStatus, "空位").in(Beds::getEmployeeId, bo.getId());
//            bedsPlusService.update(update_beds_sql2);
//            bo.setRoomNumber("");
//            bo.setAllocated(null);
            SysNotice notice=new SysNotice();
            String noticeTitle = String.format("%s 已离职", bo.getFullName());
            notice.setNoticeTitle(noticeTitle);
            notice.setNoticeType("离职");
            notice.setStatus("0");
            sysNoticeService.insertNotice(notice);
        } else if (bo.getDelFlag().equals("2")) {
            //Employee employeeModel=employeePlusService.getById(bo.getId());
            if (bo.getAccommodation().equals("是") && bo.getRoomNumber()!=null){
                SysNotice notice=new SysNotice();
                String noticeTitle = String.format("%s 已被删除", bo.getFullName());
                notice.setNoticeTitle(noticeTitle);
                notice.setNoticeType("离职");
                notice.setStatus("0");
                sysNoticeService.insertNotice(notice);
            }
        }
        return toAjax(employeePlusService.updateById(bo));
    }

    /**
     * 删除员工
     *
     * @param ids 主键串
     */
    @Log(title = "员工", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        LambdaUpdateWrapper<Employee> update_Employee_sql = new LambdaUpdateWrapper<Employee>().set(Employee::getDelFlag, "2").in(Employee::getId, ids);
        employeePlusService.update(update_Employee_sql);
        for (Long employeeid:ids) {
            Employee employeeModel=employeePlusService.getById(employeeid);
            if (employeeModel.getAccommodation().equals("是") && employeeModel.getRoomNumber()!=null){
                SysNotice notice=new SysNotice();
                String noticeTitle = String.format("%s 已被删除", employeeModel.getFullName());
                notice.setNoticeTitle(noticeTitle);
                notice.setNoticeType("离职");
                notice.setStatus("0");
                sysNoticeService.insertNotice(notice);
            }

        }
        return toAjax(true);
    }

    /**
     * 重新生成pdf
     *
     * @param id 主键
     */
    @GetMapping("/reCreatPdf/{id}")
    public R<Void> reCreatPdf(@NotNull(message = "主键不能为空") @PathVariable Long id) throws DocumentException, IOException {
        Employee entity = employeePlusService.getById(id);
        if (entity.getRoomNumber()!=null&&!entity.getRoomNumber().isEmpty()){
            entity.setBeddetail(bedsPlusService.getbedDetailByid(entity.getRoomNumber()));
        }
        // 创建 EmployeePdf 对象
        EmployeePdf employeePdf = new EmployeePdf();
        if (entity.getEntryDate()!=null) {
            employeePdf.setEntryDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, entity.getEntryDate()));
        }
        if (entity.getAge() != null) {
            employeePdf.setAge(entity.getAge());
        } else {
            employeePdf.setAge(0L); // 如果 age 为 null，将其设置为默认值，这里设置为 0
        }
        employeePdf.setJobNumber(entity.getJobNumber());
        employeePdf.setFullName(entity.getFullName());
        employeePdf.setDepartment(entity.getDepartment());
        employeePdf.setPosition(entity.getPosition());
        employeePdf.setGender(entity.getGender());
        employeePdf.setEthnicity(entity.getEthnicity());
        employeePdf.setIdNumber(entity.getIdNumber());
        employeePdf.setHomeAddress(entity.getHomeAddress());
        employeePdf.setResidentialAddress(entity.getResidentialAddress());
        employeePdf.setContactNumber(entity.getContactNumber());
        employeePdf.setEmergencyContactPerson(entity.getEmergencyContactPerson());
        employeePdf.setEmergencyContactNumber(entity.getEmergencyContactNumber());
        employeePdf.setEducation(entity.getEducation());
        employeePdf.setMajor(entity.getMajor());
        employeePdf.setTechnicalTitle(entity.getTechnicalTitle());
        employeePdf.setAccommodation(entity.getAccommodation());
        employeePdf.setBeddetail(entity.getBeddetail());
        employeePdf.setFreeMeal(entity.getFreeMeal());
        employeePdf.setJobchange(entity.getJobchange());
        employeePdf.setSecondemployment(entity.getSecondemployment());
        employeePdf.setPositionLevel(entity.getPositionLevel());
        employeePdf.setFujianmanage(entity.getFujianmanage());
        if (entity.getInsuranceStartDate()!=null) {
            employeePdf.setInsuranceStartDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM, entity.getInsuranceStartDate()));
        }
        if (entity.getInsuranceEndDate()!=null) {
            employeePdf.setInsuranceEndDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM, entity.getInsuranceEndDate()));
        }
        if (entity.getHousingFundStartDate()!=null) {
            employeePdf.setHousingFundStartDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM, entity.getHousingFundStartDate()));
        }

        employeePdf.setRuralMedicalInsurance(entity.getRuralMedicalInsurance());
        employeePdf.setInsurancePacific(entity.getInsurancePacific());
        employeePdf.setInsuranceCpic(entity.getInsuranceCpic());
        employeePdf.setInsuranceChinalife(entity.getInsuranceChinalife());
        employeePdf.setWaiveSocialInsurance(entity.getWaiveSocialInsurance());
        employeePdf.setSocialInsurance(entity.getSocialInsurance());
        if (entity.getFirstContractExpiryDate()!=null) {
            employeePdf.setFirstContractExpiryDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, entity.getFirstContractExpiryDate()));
        }
        if (entity.getSecondContractExpiryDate()!=null) {
            employeePdf.setSecondContractExpiryDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, entity.getSecondContractExpiryDate()));
        }
        if (entity.getThirdContractExpiryDate()!=null) {
            employeePdf.setThirdContractExpiryDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, entity.getThirdContractExpiryDate()));
        }
        if (entity.getFourthContractExpiryDate()!=null) {
            employeePdf.setFourthContractExpiryDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, entity.getFourthContractExpiryDate()));
        }
        if (entity.getFifthContractExpiryDate()!=null) {
            employeePdf.setFifthContractExpiryDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, entity.getFifthContractExpiryDate()));
        }
        if (entity.getDepartureDate()!=null) {
            employeePdf.setDepartureDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, entity.getDepartureDate()));
        }
        employeePdf.setDepartureStatus(entity.getDepartureStatus());
        employeePdf.setDepartureReason(entity.getDepartureReason());
        employeePdf.setImg(entity.getImg());
        employeePdf.setCrime(entity.getCrime());
        employeePdf.setRemarks(entity.getRemarks());
        employeePdf.setContractRemarks(entity.getContractRemarks());
        employeePdf.setEmployeeRank(entity.getEmployeeRank());//职级
        employeePdf.setRankSalary(entity.getRankSalary());//职级工资
        employeePdf.setPerformanceLevel(entity.getPerformanceLevel());//绩效档位
        employeePdf.setPerformanceAmount(entity.getPerformanceAmount());//绩效金额
        employeePdf.setMonthlyRent(entity.getMonthlyRent());//月押金额
        employeePdf.setSkillSalary(entity.getSkillSalary());//技能工资
        employeePdf.setTaxSubsidy(entity.getTaxSubsidy());//个税补贴
        pdfTool pdfTool = new pdfTool();
        Long filename = System.currentTimeMillis();
        if (pdfTool.creatPdf(employeePdf, filename)) {
            entity.setPdfurl(filename + ".pdf");
            employeePlusService.updateById(entity);
            return R.ok();
        }
        return R.fail();
    }

    /**
     * 头像上传
     *
     * @param avatarfile 头像
     */
    @SaIgnore
    @Log(title = "员工头像", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/avatar", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<Map<String, Object>> avatar(@RequestPart("avatarfile") MultipartFile avatarfile) throws IOException {
        Map<String, Object> ajax = new HashMap<>();
        if (!avatarfile.isEmpty()) {
            String extension = FileUtil.extName(avatarfile.getOriginalFilename());
            if (!StringUtils.equalsAnyIgnoreCase(extension, MimeTypeUtils.IMAGE_EXTENSION)) {
                return R.fail("文件格式不正确，请上传" + Arrays.toString(MimeTypeUtils.IMAGE_EXTENSION) + "格式");
            }
            String BaseDir = FileUploadUtils.getDefaultBaseDir() + "/avatar";
            String avatar = FileUploadUtils.upload(BaseDir, avatarfile);
            ajax.put("imgUrl", avatar);
            return R.ok(ajax);
        }
        return R.fail("上传图片异常，请联系管理员");
    }
    /**
     * 提交分配宿舍的申请
     *
     * @param ids 主键串
     */
    @Log(title = "员工", businessType = BusinessType.DELETE)
    @PostMapping(value = "/allocated/{ids}")
    public R<Void> allocated(@NotEmpty(message = "主键不能为空") @PathVariable Long[] ids) {
        LambdaUpdateWrapper<Employee> updateWrapper = new LambdaUpdateWrapper<Employee>()
            .set(Employee::getAllocated, "待办")
            .and(i -> i.isNull(Employee::getRoomNumber)
                .or()
                .eq(Employee::getRoomNumber, "")
            ).eq(Employee::getAccommodation,"是")
            .in(Employee::getId, ids);
        employeePlusService.update(updateWrapper);
        return toAjax(true);
    }

    /**
     * 驳回员工的住宿申请
     * 待办状态变为驳回
     */
    @Log(title = "驳回员工的住宿申请", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PostMapping(value = "/editAllocatedToReject/{id}")
    public R<Void> editAllocatedToReject(@PathVariable Long id) {
        LambdaUpdateWrapper<Employee> update_sql = new LambdaUpdateWrapper<Employee>().set(Employee::getAllocated, "驳回").eq(Employee::getId, id);
        return toAjax(employeePlusService.update(update_sql));
    }
    /**
     * 查询合同快要到期的员工数据
     */
    @GetMapping("/ContractExpirationReminder")
    public List<Employee> ContractExpirationReminder(Employee query) {
     return    employeePlusService.ContractExpirationReminder(query);
    }
    /**
     * 查询合同快要到期的员工数据
     */
    @PostMapping("/ContractExpirationReminderExport")
    public void ContractExpirationReminderExport(EmployeeVo query,HttpServletResponse response) throws ParseException{
        List<EmployeeVo> list= employeePlusService.ContractExpirationReminderVo(query);
        ExcelUtilPlus<EmployeeVo> util = new ExcelUtilPlus<EmployeeVo>(EmployeeVo.class);
        util.exportExcel(response, list, "合同到期员工");

    }
    /**
     * 退休年龄提醒，男60周岁，女50周岁提醒。
     */
    @GetMapping("/retirementReminder")
    public List<Employee> retirementReminder(Employee query) {
        return    employeePlusService.retirementReminder(query);
    }
    @PostMapping("/retirementReminderExport")
    public void retirementReminderExport(EmployeeVo query,HttpServletResponse response) throws ParseException{
        List<EmployeeVo> list= employeePlusService.retirementReminderVO(query);
        ExcelUtilPlus<EmployeeVo> util = new ExcelUtilPlus<EmployeeVo>(EmployeeVo.class);
        util.exportExcel(response, list, "快退休员工");

    }
}
